const deviceModel = require("../../../../model/device");
const keepAliveAck = require("../../ack/keepaliveAck");
const log4js = require('../../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const sip = require("sip");
const deviceCache = require("../../../../db/deviceCache");

module.exports={
    /**
     * 心跳处理
     * @param rq
     * @param deviceId
     * @param channelId
     * @returns {Promise<void>}
     */
    async handle(rq, deviceId, channelId){
        const via0 = rq.headers.via[0];
        // 通过心跳修正数据库里的host port值
        let hasUpdate=false;
        if (via0.params && via0.params.rport) {
            const deviceInfo =await deviceModel.getDeviceByDeviceId(deviceId);
            // logger.info('[心跳处理]', deviceInfo);
            if(via0.params.received !== deviceInfo.sip_command_host) {

                deviceCache.registry[deviceId].sip_command_host = deviceInfo.sip_command_host = via0.params.received;
                deviceCache.registry[deviceId].sip_command_port = deviceInfo.sip_command_port = via0.params.rport;
                deviceCache.registry[deviceId].uri = deviceInfo.uri = `sip:${deviceId}@${deviceInfo.sip_command_host}:${deviceInfo.sip_command_port}`
                deviceCache.registry[deviceId].online = deviceInfo.online=1;
                await deviceModel.update(deviceInfo);
                hasUpdate = true;
            }
        }
        if(!hasUpdate){
            await deviceModel.register(deviceId, 1);
        }

        // 有些通道号填写有问题，下面一句可以默认生成channelId与deviceId相同的子通道
        // await channelModel.updateOnline(deviceId, channelId, 1);
        let alive = keepAliveAck.generate(rq);
        sip.send(alive);
    }
}
